#include "../../exatron/inc/common.h"

#define TEST_SCK

#define NB_TEST 300


Socket_t sock;

void client(char *ip, int porta);

int main(int argc, char *argv[])
{
	int porta;
	int i=0;

	if(argc < 3)
	{
		printf("\nUso: st_client IP Porta\r\n\n");
		return 0;
	}
	else
	{
		porta = atoi(argv[2]);

		for(i=0;i<11;i++)
		{
			if(!fork())
			{
				client(argv[1], porta);
				exit(1);
			}
			usleep(1000000/11); /* Espera 1/11s */
		}
	}

	printf("\nPressione enter para sair...\r\n");

	fgetc(stdin);

	system("killall st_client");

	return 0;
}

/* External functions --------------------------------------------------------*/

/** @defgroup TCP_Functions
  * @{
  */

/**
  * @brief  Função para conectar a um socket server.
  * @param  SocketID_t: ID do socket client
  * @param  char *ip: IP do server
  * @param  int porta: Porta a se conectar
  * @retval Devolve pela serial Result_t
  */
void client(char *ip, int porta)
{
    int n=0;

    char temp_buf[NB_TEST];

    memset(&sock,0,sizeof(sock));

    /* Abre o socket */
    sock.clifd = socket(AF_INET, SOCK_STREAM, 0);
    if (sock.clifd < 0)
    {
		printf("Error on open socket\n\r");
		exit(EXIT_FAILURE);
    }

    sock.ID = 0;

    sock.seraddr.sin_port = htons(porta);
    sock.seraddr.sin_family = AF_INET;
    sock.seraddr.sin_addr.s_addr = inet_addr(ip);

    if (connect(sock.clifd,(struct sockaddr *)&sock.seraddr,sizeof(sock.seraddr))<0)
    {
		printf("Error on connect\n\r");
		exit(EXIT_FAILURE);
    }

    //fcntl (sock.clifd, F_SETFL, O_NONBLOCK);

    bzero(sock.Data.buf_rx,RX_BUF_LEN);

	#ifdef TEST_SCK
    memset(temp_buf, 'A', NB_TEST);
	#endif

   	while(1)
    {
		#ifdef TEST_SCK
		n = 0;

		n = write(sock.clifd, temp_buf, NB_TEST);

		bzero(sock.Data.buf_rx, sizeof(sock.Data.buf_rx));
		n = read(sock.clifd, sock.Data.buf_rx, sizeof(sock.Data.buf_rx));

		printf("Recebido: %s\r\n", sock.Data.buf_rx);

		sleep(1);
		//usleep(500000);
		#endif
    }

    close(sock.clifd);
    close(sock.serfd);

    exit(EXIT_SUCCESS);
}
